package com.itheima.travel.service.impl;

import com.itheima.travel.dao.OrderDao;
import com.itheima.travel.dao.OrderItemDao;
import com.itheima.travel.domain.*;
import com.itheima.travel.service.OrderService;
import com.itheima.travel.utils.CartUtils;
import com.itheima.travel.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;


@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private CartUtils cartUtils;

    @Transactional
    @Override
    public Order save(User user, Address address) {
        //1. 通过用户得到购物车
        Cart cart = cartUtils.getCartFromRedis(user);
        //2. 创建订单，设置基础数据
        Order order = new Order();
        //1. 随机生成订单号
        order.setOid(UuidUtils.simpleUuid());
        //2. 下单时间为现在的时间
        order.setOrdertime(new Date());
        //3. 订单总金额从购物车中获取
        order.setTotal(cart.getCartTotal());
        //4. 设置为未支付订单
        order.setState(0);
        //5. 设置：收货人，收货地址，电话
        order.setAddress(address.getAddress());
        order.setTelephone(address.getTelephone());
        order.setContact(address.getContact());
        //6. 设置所属用户的uid
        order.setUid(user.getUid());
        //3. 调用DAO保存订单
        orderDao.save(order);
        //4. 遍历购物项，创建订单项集合
        LinkedHashMap<Integer, CartItem> cartItemMap = cart.getCartItemMap();
        for (CartItem cartItem:cartItemMap.values()){
        //1. 创建订单项
            OrderItem orderItem = new OrderItem();
            //2. 设置：下单时间，未支付，数量，商品小计，商品rid，订单oid
            //3. 添加到订单项集合中
            orderItem.setItemtime(new Date());
            orderItem.setState(0);
            orderItem.setNum(cartItem.getNum());
            orderItem.setSubtotal(order.getTotal());
            orderItem.setRid(cartItem.getRoute().getRid());
            orderItem.setOid(order.getOid());
            //4. 调用DAO保存每一项订单
            orderItemDao.save(orderItem);
        }
        //6. 清空购物车
        cartUtils.removeCart(user);
        //7. 返回订单对象
        return order;
    }

    @Override
    public void updateState(Map<String, String> param) {
        String oid = param.get("out_trade_no");
        String state = param.get("result_code");

        if ("SUCCESS".equalsIgnoreCase(state)){
            orderDao.updateState(oid);
            orderItemDao.updateState(oid);
        }else {
            throw new RuntimeException("支付失败");
        }
    }

    @Override
    public boolean isPay(String oid) {
        Order order = orderDao.findByOid(oid);
        return order.getState()==1?true:false;
    }
}
